<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/20
 * Time: 下午11:24
 */

namespace common\logic;


use common\models\RentingImageModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class RentingImageLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return RentingImageModel::find();
    }


    /**
     *
     * 取第一张图片
     * @param $houseId
     *
     * @return array
     */
    public function getFirstImage($houseId){
        $data = $this->getQuery(['hid'=>$houseId],[],['hid','img_path'],['id'=>SORT_ASC])->groupBy(['hid'])->all();
        if(empty($data)){
            return [];
        }

        return ArrayHelper::map($data,'hid','img_path');
    }

    /**
     * 房源的所有图片
     *
     * @param $houseId
     *
     * @return array|RentingImageModel[]
     */
    public function getAll($houseId){
        return $this->_all(['hid' => $houseId]);
    }

    public function saveFile($house_id,$key){
        if ($_FILES && !empty($_FILES['RentingImageModel']['name']['img_path'][$key])) {
            $filePath = "/upload/renting/{$house_id}/";
            $fileName = $filePath . uniqid() . '.' . pathinfo($_FILES['RentingImageModel']['name']['img_path'][$key], PATHINFO_EXTENSION);
            $filePath = \Yii::getAlias('@webroot') . $filePath;
            if (!file_exists($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $savePath = \Yii::getAlias('@webroot') . $fileName;
            if (move_uploaded_file($_FILES['RentingImageModel']['tmp_name']['img_path'][$key], $savePath)) {
                return $fileName;
            }
        }
        return '';
    }
}